import type { Method } from 'alova';

import { useAppConfig } from '@vben/hooks';
import { preferences } from '@vben/preferences';
import { useAccessStore } from '@vben/stores';

import { useAuthStore } from '#/store';
import { createAlovaInstance } from '#/utils/alova';

import { refreshTokenApi } from './core';

function formatToken(token: null | string) {
  return token ? `Bearer ${token}` : null;
}
function assignToken(method: Method) {
  const accessStore = useAccessStore();

  method.config.headers.Authorization = formatToken(accessStore.accessToken);
}

/**
 * 刷新token逻辑
 */
async function doRefreshToken() {
  const accessStore = useAccessStore();
  const resp = await refreshTokenApi();
  const newToken = resp.data;
  accessStore.setAccessToken(newToken);
  return newToken;
}

/**
 * 重新认证逻辑
 */
async function doReAuthenticate() {
  console.warn('Access token or refresh token is invalid or expired. ');
  const accessStore = useAccessStore();
  const authStore = useAuthStore();
  accessStore.setAccessToken(null);
  if (
    preferences.app.loginExpiredMode === 'modal' &&
    accessStore.isAccessChecked
  ) {
    accessStore.setLoginExpired(true);
  } else {
    await authStore.logout();
  }
}

const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

export const request = createAlovaInstance({
  baseURL: apiURL,
  assignToken,
  doReAuthenticate,
  doRefreshToken,
});
